//
//  LaunchPerformanceMonitor.swift
//  CMB250716
//
//  Created by Assistant on 2025-01-11.
//

import Foundation
import SwiftUI

/// 启动性能监控工具
class LaunchPerformanceMonitor: ObservableObject {
    static let shared = LaunchPerformanceMonitor()
    
    // MARK: - 性能指标
    
    @Published var isMonitoring: Bool = false
    @Published var launchStartTime: Date?
    @Published var dataLoadStartTime: Date?
    @Published var dataLoadEndTime: Date?
    @Published var launchEndTime: Date?
    
    // MARK: - 计算属性
    
    /// 总启动时间（秒）
    var totalLaunchTime: TimeInterval? {
        guard let start = launchStartTime, let end = launchEndTime else { return nil }
        return end.timeIntervalSince(start)
    }
    
    /// 数据加载时间（秒）
    var dataLoadingTime: TimeInterval? {
        guard let start = dataLoadStartTime, let end = dataLoadEndTime else { return nil }
        return end.timeIntervalSince(start)
    }
    
    /// 启动性能等级
    var performanceGrade: PerformanceGrade {
        guard let totalTime = totalLaunchTime else { return .unknown }
        
        switch totalTime {
        case 0..<1.0:
            return .excellent
        case 1.0..<2.0:
            return .good
        case 2.0..<3.0:
            return .fair
        default:
            return .poor
        }
    }
    
    private init() {
        if LaunchConfig.enablePerformanceMonitoring {
            startMonitoring()
        }
    }
    
    // MARK: - 监控方法
    
    /// 开始监控启动性能
    func startMonitoring() {
        guard !isMonitoring else { return }
        
        isMonitoring = true
        launchStartTime = Date()
        
        if LaunchConfig.logLaunchTime {
            print("[LaunchMonitor] 启动监控开始: \(formatTime(launchStartTime!))")
        }
    }
    
    /// 标记数据加载开始
    func markDataLoadingStart() {
        guard isMonitoring else { return }
        
        dataLoadStartTime = Date()
        
        if LaunchConfig.logLaunchTime {
            print("[LaunchMonitor] 数据加载开始: \(formatTime(dataLoadStartTime!))")
        }
    }
    
    /// 标记数据加载完成
    func markDataLoadingEnd() {
        guard isMonitoring else { return }
        
        dataLoadEndTime = Date()
        
        if LaunchConfig.logLaunchTime {
            let loadTime = dataLoadingTime ?? 0
            print("[LaunchMonitor] 数据加载完成: \(formatTime(dataLoadEndTime!)), 耗时: \(String(format: "%.3f", loadTime))秒")
        }
    }
    
    /// 标记启动完成
    func markLaunchComplete() {
        guard isMonitoring else { return }
        
        launchEndTime = Date()
        
        if LaunchConfig.logLaunchTime {
            let totalTime = totalLaunchTime ?? 0
            print("[LaunchMonitor] 启动完成: \(formatTime(launchEndTime!)), 总耗时: \(String(format: "%.3f", totalTime))秒")
            print("[LaunchMonitor] 性能等级: \(performanceGrade.description)")
            
            // 性能警告
            if totalTime > LaunchConfig.performanceThreshold {
                print("[LaunchMonitor] ⚠️ 启动时间超过阈值 (\(LaunchConfig.performanceThreshold)秒)")
            }
        }
        
        // 重置监控状态
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            self.resetMonitoring()
        }
    }
    
    /// 重置监控状态
    func resetMonitoring() {
        isMonitoring = false
        launchStartTime = nil
        dataLoadStartTime = nil
        dataLoadEndTime = nil
        launchEndTime = nil
    }
    
    // MARK: - 辅助方法
    
    private func formatTime(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm:ss.SSS"
        return formatter.string(from: date)
    }
    
    /// 获取性能报告
    func getPerformanceReport() -> PerformanceReport? {
        guard let totalTime = totalLaunchTime else { return nil }
        
        return PerformanceReport(
            totalLaunchTime: totalTime,
            dataLoadingTime: dataLoadingTime ?? 0,
            performanceGrade: performanceGrade,
            timestamp: Date()
        )
    }
}

// MARK: - 数据模型

/// 性能等级
enum PerformanceGrade: String, CaseIterable {
    case excellent = "优秀"
    case good = "良好"
    case fair = "一般"
    case poor = "较差"
    case unknown = "未知"
    
    var description: String {
        switch self {
        case .excellent:
            return "优秀 (<1秒)"
        case .good:
            return "良好 (1-2秒)"
        case .fair:
            return "一般 (2-3秒)"
        case .poor:
            return "较差 (>3秒)"
        case .unknown:
            return "未知"
        }
    }
    
    var color: Color {
        switch self {
        case .excellent:
            return .green
        case .good:
            return .blue
        case .fair:
            return .orange
        case .poor:
            return .red
        case .unknown:
            return .gray
        }
    }
}

/// 性能报告
struct PerformanceReport {
    let totalLaunchTime: TimeInterval
    let dataLoadingTime: TimeInterval
    let performanceGrade: PerformanceGrade
    let timestamp: Date
    
    var formattedTotalTime: String {
        return String(format: "%.3f秒", totalLaunchTime)
    }
    
    var formattedDataLoadTime: String {
        return String(format: "%.3f秒", dataLoadingTime)
    }
}

// MARK: - SwiftUI 扩展

extension LaunchPerformanceMonitor {
    /// 创建性能监控视图修饰符
    func performanceMonitorModifier() -> some ViewModifier {
        return PerformanceMonitorModifier(monitor: self)
    }
}

struct PerformanceMonitorModifier: ViewModifier {
    let monitor: LaunchPerformanceMonitor
    
    func body(content: Content) -> some View {
        content
            .onAppear {
                if LaunchConfig.enablePerformanceMonitoring {
                    monitor.startMonitoring()
                }
            }
    }
}

// MARK: - View 扩展

extension View {
    /// 添加启动性能监控
    func monitorLaunchPerformance() -> some View {
        self.modifier(LaunchPerformanceMonitor.shared.performanceMonitorModifier())
    }
}